package com.jielihaofeng.atguigu.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author Johnnie Wind
 * @description 应用实例2 - 本地文件读数据
 * @date 2021/11/25 11:25
 */
public class NioFileChannel02 {
    public static void main(String[] args) throws Exception {

        // 创建一个文件输入流
        File file = new File("d:\\file01.txt");
        FileInputStream fileInputStream = new FileInputStream(file);

        // 通过fileInputStream 获取对应的channel
        FileChannel fileChannel = fileInputStream.getChannel();

        // 创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());

        // 将通道数据读入缓冲区
        fileChannel.read(byteBuffer);

        // 将缓冲区的字节转为字符串输出
        System.out.println(new String(byteBuffer.array()));
        fileInputStream.close();
    }
}
